package cn.stylefeng.guns.modular.rest.tool;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.app.model.params.MovingPalletsmergeParam;
import cn.stylefeng.guns.modular.basic.entity.BasicArea;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.entity.BasicPosition;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.service.BasicAreaService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.tool.entity.ToolStorageStock;
import cn.stylefeng.guns.modular.tool.model.params.ToolBtnShiftParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolRepairGoodsParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolStorageStockParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolStorageStockResult;
import cn.stylefeng.guns.modular.tool.service.ToolRepairGoodsService;
import cn.stylefeng.guns.modular.tool.service.ToolStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 云仓移库
 */
@Controller
@RequestMapping("/rest/toolRepairGoods")
public class restToolRepairGoodsController extends BaseController{

    @Autowired
    private ToolStorageStockService toolStorageStockService;
    @Autowired
    private UserAop userAop;
    @Autowired
    private ToolRepairGoodsService toolRepairGoodsService;
    @Autowired
    private BasicPositionService basicPositionService;
    @Autowired
    private BasicAreaService basicAreaService;
    @Autowired
    private BasicWarehouseService basicWarehouseService;
    @Autowired
    private BasicGoodsService basicGoodsService;
    
    /**
     * 移库
     * @param ids
     * @param aimpositionId
     * @return
     */
    @ResponseBody
    @RequestMapping("/repairGoods")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData repairGoods(Long[] ids,String[] numlist, Long aimpositionId,String aimpositionNumber) {
    	User user = userAop.getUser();
    	if(ToolUtil.isEmpty(aimpositionId)) {
    		if(ToolUtil.isNotEmpty(aimpositionNumber)) {
    			BasicPositionParam basicPositionParam = new BasicPositionParam();
    			basicPositionParam.setPositionNumber(aimpositionNumber);
    			basicPositionParam.setDeliverId(user.getDeliverId());
    			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    			if(basicPositionResult == null) {
    				return ResponseData.error("目的库位不存在！");
    			} else {
    				aimpositionId = Long.parseLong(basicPositionResult.getId().toString());
    			}
    		} else {
				return ResponseData.error("请选择目的库位！");
    		}
    	}

    	List<ToolStorageStockParam> _list = new ArrayList<ToolStorageStockParam>();
    	for (int i = 0; i < ids.length; i++) {
    		ToolStorageStockParam o = new ToolStorageStockParam();
    		o.setId(Integer.parseInt(ids[i].toString()));
    		o.setShiftNum(numlist[i]);
    		_list.add(o);
		}

        BasicPosition basicPosition = basicPositionService.getById(aimpositionId);
        BasicArea basicArea  = basicAreaService.getById(basicPosition.getPositionAreaId());
        BasicWarehouse basicWarehouse = basicWarehouseService.getById(basicArea.getAreaWarehouseId());
		List<ToolStorageStockParam> storageList = new ArrayList<ToolStorageStockParam>();
		List<ToolRepairGoodsParam> repairGoodsList = new ArrayList<ToolRepairGoodsParam>();
		BigDecimal as = new BigDecimal("0");
    	for (ToolStorageStockParam p : _list) {
    		ToolStorageStock storageStock = toolStorageStockService.getById(p.getId());
    		BigDecimal kcshu = new BigDecimal(storageStock.getNum());//库存数
    		BigDecimal ykshu = new BigDecimal(p.getShiftNum());//补货数
    		if(kcshu.compareTo(as) != 1) {
    			continue;
    		}
    		if(ykshu.compareTo(as) != 1) {
    			continue;
    		}
    		if(storageStock.getPositionId().equals(aimpositionId)) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
				return ResponseData.error("源库位与目的地不可一致");
    		}
    		if(ykshu.compareTo(kcshu) == 1) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
				return ResponseData.error("不可大于库存数");
    		}
    		ToolRepairGoodsParam repairGoodsParam = new ToolRepairGoodsParam();
    		repairGoodsParam.setSourcewarehouseId(storageStock.getWarehouseId());
    		repairGoodsParam.setSourcewarehouseName(storageStock.getWarehouseName());
    		repairGoodsParam.setSourceareaId(storageStock.getAreaId());
    		repairGoodsParam.setSourceareaNumber(storageStock.getAreaNumber());
    		repairGoodsParam.setSourcepositionId(storageStock.getPositionId());
    		repairGoodsParam.setSourcepositionNumber(storageStock.getPositionNumber());
    		repairGoodsParam.setNum(p.getShiftNum());
    		repairGoodsParam.setAimwarehouseId(Long.parseLong(basicArea.getAreaWarehouseId().toString()));
    		repairGoodsParam.setAimwarehouseName(basicWarehouse.getWarehouseName());
    		repairGoodsParam.setAimareaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
    		repairGoodsParam.setAimareaNumber(basicArea.getAreaNumber());
    		repairGoodsParam.setAimpositionId(aimpositionId);
    		repairGoodsParam.setAimpositionNumber(basicPosition.getPositionNumber());
    		repairGoodsParam.setGoodsName(storageStock.getGoodsName());
    		repairGoodsParam.setGoodsNumber(storageStock.getGoodsNumber());
    		repairGoodsParam.setGoodsId(storageStock.getGoodsId());
    		repairGoodsParam.setDeliverId(user.getDeliverId());
    		repairGoodsParam.setDeptId(user.getDeptId());
    		repairGoodsParam.setCreateTime(new Date());
    		repairGoodsParam.setCreateName(user.getName());
    		repairGoodsList.add(repairGoodsParam);

    		if(ykshu.compareTo(kcshu) == 0) {//整托移库  有相同属性库存进行合并
    			ToolStorageStockParam xiangtongParam = new ToolStorageStockParam();
    			xiangtongParam.setPositionId(aimpositionId);
    			xiangtongParam.setGoodsId(storageStock.getGoodsId());
    			ToolStorageStockResult xiangtongr = toolStorageStockService.findBySpec(xiangtongParam);
    			if(xiangtongr != null) {
					BigDecimal xtnum = new BigDecimal(xiangtongr.getNum());
        			BasicGoods basicGoods = basicGoodsService.getById(storageStock.getGoodsId());
        			ToolStorageStockParam supdate = new ToolStorageStockParam();
        			ToolUtil.copyProperties(xiangtongr, supdate);
        			BigDecimal xshu = kcshu.add(xtnum).setScale(2, BigDecimal.ROUND_HALF_DOWN);//相加
        			supdate.setNum(xshu.toString());
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
    					BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
    					supdate.setStockWeight(w.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//重量
    				} else {
    					supdate.setStockWeight("1");//重量
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
    					BigDecimal gv = new BigDecimal(basicGoods.getGoodsVolume());
    					supdate.setStockVolume(gv.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
    				} else {
    					supdate.setStockVolume("1");//体积
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsCharging())) {
    					BigDecimal price = new BigDecimal(basicGoods.getGoodsCharging());
    					supdate.setStockMoney(price.multiply(xshu).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//库存金额
    					supdate.setUnitprice(basicGoods.getGoodsCharging());//单价
    				} else {
    					supdate.setUnitprice("1");//单价
    					supdate.setStockMoney(xshu.toString());//库存金额
    				}
    				toolStorageStockService.update(supdate);//更新相同库存
    				ToolStorageStockParam depdate = new ToolStorageStockParam();
    				depdate.setId(storageStock.getId());
    				toolStorageStockService.delete(depdate);
    			} else {
    				ToolStorageStockParam supdate = new ToolStorageStockParam();
    				ToolUtil.copyProperties(storageStock, supdate);
    				supdate.setWarehouseId(Long.parseLong(basicArea.getAreaWarehouseId().toString()));
    				supdate.setWarehouseName(basicWarehouse.getWarehouseName());
    				supdate.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
    				supdate.setAreaNumber(basicArea.getAreaNumber());
    				supdate.setPositionId(aimpositionId);
    				supdate.setPositionNumber(basicPosition.getPositionNumber());
    				toolStorageStockService.update(supdate);
    			}
    		}
    		if(ykshu.compareTo(kcshu) == -1) {//移出部分	有相同属性库存进行合并
    			BasicGoods basicGoods = basicGoodsService.getById(storageStock.getGoodsId());
    			ToolStorageStockParam supdate = new ToolStorageStockParam();
    			ToolUtil.copyProperties(storageStock, supdate);
    			BigDecimal sykcshu = kcshu.subtract(ykshu).setScale(2, BigDecimal.ROUND_HALF_DOWN);//剩余库存
    			supdate.setNum(sykcshu.toString());
				if (ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
					BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
					supdate.setStockWeight(w.multiply(sykcshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//重量
				} else {
					supdate.setStockWeight("1");//重量
				}
				
				if (ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
					BigDecimal gv = new BigDecimal(basicGoods.getGoodsVolume());
					supdate.setStockVolume(gv.multiply(sykcshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
				} else {
					supdate.setStockVolume("1");//体积
				}
				
				if (ToolUtil.isNotEmpty(basicGoods.getGoodsCharging())) {
					BigDecimal price = new BigDecimal(basicGoods.getGoodsCharging());
					supdate.setStockMoney(price.multiply(sykcshu).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//库存金额
					supdate.setUnitprice(basicGoods.getGoodsCharging());//单价
				} else {
					supdate.setUnitprice("1");//单价
					supdate.setStockMoney(sykcshu.toString());//库存金额
				}
				toolStorageStockService.update(supdate);//更新剩余库存

				ToolStorageStockParam xiangtongParam = new ToolStorageStockParam();
    			xiangtongParam.setPositionId(aimpositionId);
    			xiangtongParam.setGoodsId(storageStock.getGoodsId());
    			ToolStorageStockResult xiangtongr = toolStorageStockService.findBySpec(xiangtongParam);
    			if(xiangtongr != null) {
					BigDecimal xtnum = new BigDecimal(xiangtongr.getNum());
					ToolStorageStockParam xtupdate = new ToolStorageStockParam();
        			ToolUtil.copyProperties(xiangtongr, xtupdate);
        			BigDecimal xshu = ykshu.add(xtnum).setScale(2, BigDecimal.ROUND_HALF_DOWN);//相加
        			xtupdate.setNum(xshu.toString());
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
    					BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
    					xtupdate.setStockWeight(w.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//重量
    				} else {
    					xtupdate.setStockWeight("1");//重量
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
    					BigDecimal gv = new BigDecimal(basicGoods.getGoodsVolume());
    					xtupdate.setStockVolume(gv.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
    				} else {
    					xtupdate.setStockVolume("1");//体积
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsCharging())) {
    					BigDecimal price = new BigDecimal(basicGoods.getGoodsCharging());
    					xtupdate.setStockMoney(price.multiply(xshu).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//库存金额
    					xtupdate.setUnitprice(basicGoods.getGoodsCharging());//单价
    				} else {
    					xtupdate.setUnitprice("1");//单价
    					xtupdate.setStockMoney(xshu.toString());//库存金额
    				}
    				toolStorageStockService.update(xtupdate);//更新相同库存
    			} else {
    				ToolStorageStockParam sadd = new ToolStorageStockParam();
    				ToolUtil.copyProperties(storageStock, sadd);
    				sadd.setId(null);
    				sadd.setCreateTime(new Date());
    				sadd.setWarehouseId(Long.parseLong(basicArea.getAreaWarehouseId().toString()));
    				sadd.setWarehouseName(basicWarehouse.getWarehouseName());
    				sadd.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
    				sadd.setAreaNumber(basicArea.getAreaNumber());
    				sadd.setPositionId(aimpositionId);
    				sadd.setPositionNumber(basicPosition.getPositionNumber());
    				sadd.setNum(ykshu.toString());
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
    					BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
    					sadd.setStockWeight(w.multiply(ykshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//重量
    				} else {
    					sadd.setStockWeight("1");//重量
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
    					BigDecimal gv = new BigDecimal(basicGoods.getGoodsVolume());
    					sadd.setStockVolume(gv.multiply(ykshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
    				} else {
    					sadd.setStockVolume("1");//体积
    				}
    				
    				if (ToolUtil.isNotEmpty(basicGoods.getGoodsCharging())) {
    					BigDecimal price = new BigDecimal(basicGoods.getGoodsCharging());
    					sadd.setStockMoney(price.multiply(ykshu).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//库存金额
    					sadd.setUnitprice(basicGoods.getGoodsCharging());//单价
    				} else {
    					sadd.setUnitprice("1");//单价
    					sadd.setStockMoney(ykshu.toString());//库存金额
    				}
    				storageList.add(sadd);
    			}
    		}
		}
    	if(storageList.size() > 0) {
			toolStorageStockService.batchAddList(storageList);
    	}
    	if(repairGoodsList.size() > 0) {
    		toolRepairGoodsService.batchAddList(repairGoodsList);
    	}
        return ResponseData.success();
    }

    /**
     * 根据库位查询商品信息
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseData list(ToolStorageStockParam toolStorageStockParam) {
    	User user = userAop.getUser();
    	if(ToolUtil.isNotEmpty(toolStorageStockParam.getPositionNumber())) {
    		BasicPositionParam basicPositionParam = new BasicPositionParam();
    		basicPositionParam.setPositionNumber(toolStorageStockParam.getPositionNumber());
    		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    		if(basicPositionResult == null) {
    			return ResponseData.error("库位不存在！");
    		} else {
    			toolStorageStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
    		}
    	}
    	
        List<ToolStorageStockResult> iii = this.toolStorageStockService.findListBySpec(toolStorageStockParam);
        return ResponseData.success(iii);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/cxlist")
    public LayuiPageInfo list(ToolRepairGoodsParam toolRepairGoodsParam, String condition) {
    	User user = userAop.getUser();
    	toolRepairGoodsParam.setDeptId(user.getDeptId());
    	LayuiPageInfo LayuiPageInfo = this.toolRepairGoodsService.findPageBySpec(toolRepairGoodsParam, condition,user.getOperateId());
    	LayuiPageInfo.setCode(200);
        return LayuiPageInfo;
    }
	


}
